<template>
  <div style="position: absolute; height: 100%; width: 100%;">
    <el-container>
      <el-header>
        <div style="margin-top: 10px; text-align: right; padding-right: 30px;display: inline-block;">
          <el-button size="mini" @click="showAddRole=true">新增角色</el-button>
        </div>
        <div style="margin-top: 10px; text-align: right;display: inline-block;">
          <el-button size="mini" @click="syncPermission">同步权限</el-button>
        </div>
      </el-header>
      <el-main>
          <el-table
            :data="roleData"
            border
            style="width: 100%">
            <el-table-column prop="roleName" label="角色名称" align="center">
            </el-table-column>

            <el-table-column prop="createTime" label="创建时间" align="center">
              <template slot-scope="scope">
                    <i class="el-icon-date"/>
                    {{ scope.row.createTime | dateFilter }}
              </template>
            </el-table-column>

            <el-table-column label="更新时间" align="center">
              <template slot-scope="scope">
                    <i class="el-icon-date"/>
                    {{ scope.row.updateTime | dateFilter }}
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="355">
              <template slot-scope="scope">
                <el-button size="mini" @click="selectedRole=scope.row; showUpdateRole=true">修改</el-button>
                <el-button size="mini" type="danger" @click="deleteRole(scope.$index, scope.row)">删除</el-button>
                <el-button size="mini" type="danger" v-if="scope.row.status == 0" @click="stautsShow(scope.$index, scope.row)">启用</el-button>
                <el-button size="mini" type="warning" v-if="scope.row.status == 1" @click="stautsShow(scope.$index, scope.row)">停用</el-button>
                <el-button size="mini" type="warning" @click="selectedRoleDeploy=scope.row; showAddRoleDeploy=true">权限配置</el-button>
              </template>
            </el-table-column>
          </el-table>
      </el-main>

    </el-container>

    <el-dialog title="添加角色" :visible.sync="showAddRole" :close-on-click-modal="false" :close-on-press-escape="false">
      <addRole v-if="showAddRole" @refresh="getRoleTablePage" @closeDialog="showAddRole = false"/>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="showUpdateRole" :close-on-click-modal="false" :close-on-press-escape="false">
      <updateRole v-if="showUpdateRole" :row="selectedRole" @refresh="getRoleTablePage" @closeDialog="showUpdateRole = false"/>
    </el-dialog>

    <el-dialog title="权限配置" :visible.sync="showAddRoleDeploy" :close-on-click-modal="false" :close-on-press-escape="false">
      <roleDeploy v-if="showAddRoleDeploy" :id="selectedRoleDeploy.id"  @refresh="getRoleTablePage" @closeDialog="showAddRoleDeploy = false"/>
    </el-dialog>

  </div>
</template>

<script>
import addRole from './components/addRole.vue';
import updateRole from './components/updateRole.vue';
import roleDeploy from './components/roleDeploy.vue';
import { formatDate } from '@/utils/formatDate.js'



export default {
  components: { addRole, updateRole,roleDeploy },
  filters: {
    dateFilter(date) {
      // return formatDate(new Date(date), 'yyyy-MM-dd hh:mm:ss')
      if (date != null && date != '') {
        return formatDate(new Date(date), 'yyyy-MM-dd')
      } else {
        return ''
      }
     }
  },
  data() {
    return {
       roleData: [],
      showAddRole: false,
      showUpdateRole: false,
      showAddRoleDeploy: false,
      listLoading: true,
      selectedRoleDeploy:null,
      pageInfo: [

              {username:'sun',
              account:'123456',
              roleName:'管理员'}


      ],
      selectedRole: null,
      options: [],
      searchDate: [],
      searchData: {}
    }
  },
  created() {
    this.getRoleTablePage()
  },
  methods: {
    getRoleTablePage() {
      this.listLoading = true;
      this.$axios({
        url: '/system/role/list',
        method: 'get',
      }).then((res) => {
        if(res.code == 200) {
          this.roleData = res.data;
        }
        // this.listLoading = false
      }).catch(() => {

      })
    },
    deleteRole(index, row) {
      this.$confirm('确认删除？')
        .then(_ => {
          this.$axios({
            url: '/system/role/delete/' + row.id,
            method: 'post',
          }).then((res) => {
            if(res.code == 200){
                this.$message.success('删除角色成功！');
                this.getRoleTablePage();
            } else {
              this.$message.warning(res.desc)
            }
          }).catch(_ => {})
        }).catch(_ => {});
    },
    stautsShow(index, row){
      var userId = sessionStorage.getItem("userId");
      var userName = sessionStorage.getItem("userName");
      var token = sessionStorage.getItem("token");
      this.$axios({
        method:'post',
        url:'/sysRole/isUse',
        data:qs.stringify({ token: token, userId: userId, uName: userName,roleId: row.roleId, status: row.status})
      }).then((res) => {
        if( res.data.status == 200){
          this.$message(res.data.data)
          this.getRoleTablePage();
        }else{
          this.$message(res.data.data)
        }
      })
    },
    // 同步权限
    syncPermission() {
      var flag = true
      var _self = this
      var routeIds = []
      var permissionCodes = []

      //  检查路由操作权限码重复
      function filterOperations(operations) {
        operations.forEach((operation) => {
          if (permissionCodes.indexOf(operation.permissionCode) > -1) {
            flag = false
            _self.$message.error('权限操作码【' + operation.permissionCode + '】重复')
            throw new Error('权限操作码【' + operation.permissionCode + '】重复')
          } else {
            permissionCodes.push(operation.permissionCode)
            if (operation.operations) {
              filterOperations(operation.operations)
            }
          }
        })
      }

      //  设置路由属性
      function setAsyncRoutes(asyncRoutes) {
        asyncRoutes.forEach((asyncRoute) => {
          if (asyncRoute.id == null) {
            flag = false
            _self.$message.error('【' + asyncRoute.path + '】路由id不能为空')
            throw new Error('【' + asyncRoute.path + '】路由id不能为空')
          } else {
            if (routeIds.indexOf(asyncRoute.id) > -1) {
              flag = false
              _self.$message.error('路由id【' + asyncRoute.id + '】重复')
              throw new Error('路由id【' + asyncRoute.id + '】重复')
            } else {
              routeIds.push(asyncRoute.id)
              asyncRoute.permissionName = asyncRoute.meta.title
              if (asyncRoute.children) {
                setAsyncRoutes(asyncRoute.children)
              }
              //  检查路由操作权限码重复
              if (asyncRoute.operations != null) {
                filterOperations(asyncRoute.operations)
              }
            }
          }
        })
      }

      var asyncRoutes = []
      this.$store.state.permission.addRoutes.forEach((asyncRoute) => {
        asyncRoutes.push(asyncRoute)
      })
      asyncRoutes.splice(asyncRoutes.length - 1, 1)
      //  设置路由属性
      setAsyncRoutes(asyncRoutes)

      if (flag) {
        this.syncPermissionLoading = true
        this.$axios({
          url: '/system/permission/syncPermission',
          method: 'post',
          data: asyncRoutes
        }).then((res) => {
          if (res.code == '200') {
            this.$message.success('权限同步成功！')
            this.permissionTree = []
            this.getPermissionTree()
            this.syncPermissionLoading = false
          }
        }).catch(() => {})
      }
    },

    // getSearchDate(date) {
    //   if (date != null) {
    //     this.searchData.startTime = new Date(date[0])
    //     this.searchData.endTime = new Date(date[1])
    //   } else {
    //     this.searchData.startTime = null
    //     this.searchData.endTime = null
    //   }
    // }
  }
}
</script>
<style scoped>
  html, body {
      height:100%;
    }
    .el-container {
      height: 100%;
      display: flex;
      flex-direction: column;
      width: 100%;
      position: absolute;
      top: 0;
      left:0;
    }
    .el-header {
      margin-top: 10px;
      height: auto !important;
      min-height: 60px !important;
      flex-grow: 0;
      flex-shrink: 0;
    }
    .el-footer {
      text-align: center;
      padding: 14px 6px;
    }
    .el-main {
      height: 100%;
      padding: 10px !important;
      flex-grow: 1;
      flex-shrink: 1;
      overflow-y: auto;
    }
    .searchBtn {
      position: absolute;
      right: 30px;
    }
  /*  /deep/ .el-dialog__body{
      height: 85vh;
      overflow-y: auto;
    } */
</style>
